import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:xvideos/alert_business/normal_alert_style.dart';
import 'package:xvideos/assets_tool/images.dart';
import 'package:xvideos/hj_model/video_model.dart';
import 'package:xvideos/hj_page/mine_business/ai/ai_new_image_view.dart';
import 'package:xvideos/hj_page/mine_business/ai/mode/ai_record_entity.dart';
import 'package:xvideos/hj_utils/const.dart';
import 'package:xvideos/hj_utils/date_time_util.dart';
import 'package:xvideos/hj_utils/global.dart';
import 'package:xvideos/hj_utils/widget_utils.dart';
import 'package:xvideos/tools_base/video_download/video_download_manager.dart';
import 'package:xvideos/tools_base/video_download/video_load_record.dart';
import 'package:xvideos/tools_base/widget/net_image_widget.dart';

import '../../../video/simple_video_player_page.dart';

// StatusGenning  AiChangeFaceStatus = 0  // 未完成
// StatusComplete AiChangeFaceStatus = 1  // 已完成
// StatusRefund   AiChangeFaceStatus = -1 // 已退款
// StatusSubmit   AiChangeFaceStatus = 2  // 已提交

// ai图片换脸
// Processing   = 1 // 1、进行中
// SUCCESS      = 2 // 2、成功
// FAILURE      = 3 // 3、失败
// REFUND       = 4 // 4、退款
// StatusSubmit = 5 //5,提交

// ai脱衣
// Processing  = 1 // 1、进行中
// SUCCESS     = 2 // 2、成功
// FAILURE     = 3 // 3、失败
// REFUND      = 4 // 4、退款
// PartSuccess = 5 // 5、部分成功
// SubmitOrder = 6 // 6、已提交

//ai生成记录
class AIRecordWidget extends StatefulWidget {
  final AiRecordModel model;
  final Function()? onDeleteCallback;

  /// 0 脱衣 1视频换脸 2 图片换脸
  final int aitype;

  const AIRecordWidget(this.model, {super.key, this.aitype = 0, this.onDeleteCallback});

  @override
  State<AIRecordWidget> createState() => _AIRecordWidgetState();
}

class _AIRecordWidgetState extends State<AIRecordWidget> {
  /// 自定义进行状态 因为换脸
  ///  0 进行中 1已完成 2失败
  int get status {
    int _status = 0;
    if (widget.aitype == 1) {
      switch (widget.model.status) {
        case 0:
          _status = 0;
        case 1:
          _status = 1;
        case -1:
          _status = 2;

        case 2:
          _status = 0;
      }
      print('aitype ${widget.aitype}  status ${widget.model.status}  realstatus $_status');
      return _status;
    }
    if (widget.aitype == 0) {
      switch (widget.model.status) {
        case 1:
          _status = 0;
        case 2:
          _status = 1;
        case 3:
          _status = 2;

        case 4:
          _status = 2;
        case 5:
          _status = 2;
        case 6:
          _status = 0;
      }
      print('aitype ${widget.aitype}  status ${widget.model.status}  realstatus $_status');
      return _status;
    }

    switch (widget.model.status) {
      case 1:
        _status = 0;
      case 2:
        _status = 1;
      case 3:
        _status = 2;

      case 4:
        _status = 2;
      case 5:
        _status = 0;
    }

    print('aitype ${widget.aitype}  status ${widget.model.status}  realstatus $_status');
    return _status;
  }

  @override
  void initState() {
    super.initState();
    // 视频换脸
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: _itemClickHandler,
      child: Container(
          decoration: BoxDecoration(
            color: Colors.white.withOpacity(.05),
            borderRadius: BorderRadius.all(Radius.circular(12)),
          ),
          padding: EdgeInsets.symmetric(horizontal: 12, vertical: 18),
          child: Column(
            children: [
              _buildMenuTitle(),
              12.sizeBoxH,
              _buildItemCell(widget.model),
              12.sizeBoxH,
              0.5.line,
              12.sizeBoxH,
              Row(
                children: [
                  Expanded(
                    child: buildBtmLeftWidget(widget.model),
                  ),
                  _buildStateBtn(),
                ],
              )
            ],
          )),
    );
  }

  // _buildImgContent() {
  //   return Row(
  //     children: [
  //       NetworkImageLoader(
  //         imageUrl: _realImageCover(),
  //         width: 68,
  //         height: 68,
  //       ),
  //       12.sizeBoxW,
  //       Expanded(
  //         child: Column(
  //           mainAxisAlignment: MainAxisAlignment.center,
  //           crossAxisAlignment: CrossAxisAlignment.start,
  //           children: [
  //             Row(
  //               children: [
  //                 Text(
  //                   'ID',
  //                   style: TextStyle(color: Colors.white, fontSize: 16),
  //                 ),
  //                 4.sizeBoxW,
  //                 Text(
  //                   widget.model.id ?? '',
  //                   style: TextStyle(color: Colors.white.withOpacity(.6), fontSize: 12),
  //                 )
  //               ],
  //             ),
  //             9.sizeBoxH,
  //             Row(
  //               children: [
  //                 Text(
  //                   widget.model.createdAt?.utcTimeSToYMDString(gap: '.') ?? '',
  //                   style: TextStyle(color: Colors.white.withOpacity(.6), fontSize: 10),
  //                 ),
  //                 if (status == 2) ...[
  //                   InkWell(
  //                     child: Text(
  //                       '查看原因',
  //                       style: TextStyle(color: Colors.white, fontSize: 10),
  //                     ),
  //                   ).paddingSymmetric(horizontal: 12)
  //                 ]
  //               ],
  //             )
  //           ],
  //         ),
  //       ),
  //       4.sizeBoxW,
  //     ],
  //   );
  // }

  _buildMenuTitle() {
    return Row(
      children: [
        Expanded(
          child: Text(
            '创建时间：${DateTimeUtil.utc2iso(widget.model.createdAt)}',
            textAlign: TextAlign.start,
            style: TextStyle(fontSize: 12, color: Color(0xffDCDCDC)),
          ),
        ),
        _buildOperateView(),
      ],
    );
  }

  _itemClickHandler() {
    /// 查看图片
    if (widget.aitype == 0 || widget.aitype == 2) {
      if (status == 1) {
        final images = widget.model.newPic ?? [];
        if (images.isEmpty) return;
        Get.dialog(AiNewImageView(
          imageUrl: images.first,
        ));
        return;
      }
      if (status == 2) {
        showConfirm(
          title: '失败原因',
          content: "${widget.model.remark ?? ''}",
        );
        return;
      }
    }

    ///
    if (status == 1) {
      Get.to(SimpleVideoPlayerPage(videoUrl: widget.model.realVideoUrl, title: ''));
      return;
    }
    if (status == 2) {
      showConfirm(
        title: '失败原因',
        content: "${widget.model.remark ?? ''}",
      );
      return;
    }
  }

  String _realImageCover() {
    //0 进行中 1已完成 2失败
    if (status == 1) {
      //0 脱衣 1视频换脸 2 图片换脸
      if (widget.aitype == 1) {
        return widget.model.picture?.firstOrNull ?? '';
      }
      return widget.model.newPic?.first ?? '';
    }
    if (widget.aitype == 0 || widget.aitype == 2) {
      return widget.model.originPics?.firstOrNull ?? widget.model.originPic ?? '';
    }
    return widget.model.picture?.firstOrNull ?? '';
  }

  //0 进行中 1已完成 2失败
  _buildOperateView() {
    if (status == 0) {
      return InkWell(
        // onTap: () => widget.onDeleteCallback?.call(),
        child: Image.asset(
          'ai_record_more.png'.aiPath,
          height: 18,
        ),
      );
    } else if (status == 2) {
      // 处理失败
      return InkWell(
        onTap: () => widget.onDeleteCallback?.call(),
        child: Image.asset(
          'ai_record_delete.png'.aiPath,
          height: 18,
        ),
      );
    } else {
      return InkWell(
        onTap: _saveHandler,
        child: Image.asset(
          'ai_record_download.png'.aiPath,
          width: 46,
          height: 18,
        ),
      );
    }
  }

  _saveHandler() async {
    if (widget.aitype == 0) {
      final images = widget.model.newPic ?? [];
      if (images.isEmpty) return;
      Get.dialog(AiNewImageView(
        imageUrl: images.first,
      ));
      return;
    }
    bool isCached = await VideoLoadRecord.instance.isExistLoadVideoByUrl(CacheMediaType.video, widget.model.url ?? "");
    if (isCached) {
      showToast('你已经添加过缓存了');
      return;
    }
    bool isGranted = await _checkPermission();
    if (isGranted) {
      var result = await VideoDownloadManager.instance.download(url: widget.model.url ?? "");
      if (result == null) {
        VideoModel viewModel = VideoModel();
        viewModel.sourceURL = widget.model.url;
        viewModel.title = "AI换脸视频";
        viewModel.coverThumb = widget.model.newPic?.firstOrNull;
        viewModel.cover = widget.model.newPic?.firstOrNull;
        viewModel.commentCount = 0;
        viewModel.id = "-1";
        showToast("已加入缓存");
        await VideoLoadRecord.instance.saveVideoInfo(CacheMediaType.video, viewModel);
      }
    }
  }

  Future<bool> _checkPermission() async {
    var status = await Permission.storage.status;
    if (!status.isGranted) {
      status = await Permission.storage.request();
    }
    return status.isGranted;
  }

  //0 进行中 1已完成 2失败
  buildBtmLeftWidget(AiRecordModel model) {
    if (status == 0) {
      return const Text(
        "后台正在进行处理中...",
        style: TextStyle(
          color: Color(0xff989898),
          fontSize: 12,
        ),
      );
    } else if (status == 2) {
      return Text(
        "${model.remark}",
        style: const TextStyle(
          color: Color(0xffE1351F),
          fontSize: 12,
        ),
        maxLines: 2,
        overflow: TextOverflow.ellipsis,
      );
    }
    return Container();
  }

  //0 进行中 1已完成 2失败
  _buildStateBtn() {
    if (status == 0) {
      return Container(
        padding: EdgeInsets.symmetric(horizontal: 12, vertical: 4),
        decoration: BoxDecoration(
          color: Color(0xff0360FC),
          borderRadius: BorderRadius.circular(3),
        ),
        child: Text(
          '排队中',
          style: textStyle(12, Colors.white, FontWeight.w400),
        ),
      );
    } else if (status == 1) {
      return Container(
        padding: EdgeInsets.symmetric(horizontal: 12, vertical: 4),
        decoration: BoxDecoration(
          color: Color(0xffE1351F),
          borderRadius: BorderRadius.circular(3),
        ),
        child: Text(
          '已成功',
          style: textStyle(12, Colors.white, FontWeight.w400),
        ),
      );
    } else if (status == 2) {
      return Container(
        padding: EdgeInsets.symmetric(horizontal: 12, vertical: 4),
        decoration: BoxDecoration(
          color: Color(0xff3D3D3D),
          borderRadius: BorderRadius.circular(3),
        ),
        child: Text(
          '已失败',
          style: textStyle(12, Color(0xff989898), FontWeight.w400),
        ),
      );
    }
    return SizedBox.shrink();
  }

  _buildItemCell(AiRecordModel model) {
    return Container(
      height: 90.w,
      child: Row(
        children: [
          if (widget.aitype == 1 || widget.aitype == 2) ...[
            // 图片换脸,视频换脸有模块
            _buildMenuImage(widget.aitype == 2 ? model.modPic : model.modCover, isModel: true),
            Padding(
              padding: EdgeInsets.symmetric(horizontal: 3.5),
              child: Image.asset(
                'ai_record_add.webp'.aiPath,
                width: 18,
              ),
            ),
          ],
          if (model.originPics?.isNotEmpty == true && widget.aitype == 0)
            _buildMenuImage(model.originPics!.first, isOrg: true)
          else if (model.picture?.isNotEmpty == true && widget.aitype == 1)
            _buildMenuImage(model.picture!.first, isOrg: true)
          else
            _buildMenuImage(model.originPic ?? "", isOrg: true),
          Padding(
            padding: EdgeInsets.symmetric(horizontal: 3.5),
            child: Image.asset(
              'ai_record_equals.png'.aiPath,
              width: 18,
            ),
          ),
          if (widget.aitype == 1 && status == 1) // Ai换脸成功
            GestureDetector(
                onTap: () {
                  VideoModel videoModel = VideoModel()..sourceURL = model.url;
                  Get.to(SimpleVideoPlayerPage(
                    videoUrl: videoModel.realVideoUrl,
                    title: "AI生成视频",
                  ));
                },
                child: _buildMenuImage(model.cover ?? "", hasLoad: true, isNew: true, isVideoSuccess: true))
          else
            _buildMenuImage(model.newPic?.isNotEmpty == true ? model.newPic?.firstOrNull ?? "" : model.originPic ?? '',
                hasLoad: status == 1, isNew: true),
        ],
      ),
    );
  }

  // 0 进行中 1已完成 2失败
  _buildMenuImage(
    String? imagePaths, {
    bool hasLoad = false,
    bool isModel = false,
    bool isOrg = false,
    bool isNew = false,
    bool isVideoSuccess = false,
  }) {
    return GestureDetector(
      // onTap: () {
      //   // if (widget.status == 2 && isNew && imagePaths.isNotEmpty) {
      //   //   List<SwiperMediaData> datas = [];
      //
      //   //   datas.add(SwiperMediaData()
      //   //     ..isVideo = false
      //   //     ..url = ""
      //   //     ..cover = imagePaths);
      //
      //   //   Get.to(VideoAndPicSwiperPage(datas, 0), opaque: true);
      //   // }
      // },
      child: Stack(
        children: [
          Container(
            height: 90,
            decoration: const BoxDecoration(
              color: Color(0xff262626),
              borderRadius: BorderRadius.all(Radius.circular(8)),
            ),
            child: Row(
              children: [
                NetworkImageLoader(
                  width: 90.w,
                  height: 90.h,
                  imageUrl: imagePaths,
                ),
              ],
            ),
          ),
          Visibility(
              visible: !isNew,
              child: () {
                if (isModel)
                  return Container(
                    padding: EdgeInsets.symmetric(horizontal: 6, vertical: 2),
                    decoration: BoxDecoration(
                      color: Color(0xffFFD460),
                      borderRadius: BorderRadius.only(
                        topLeft: Radius.circular(8),
                        bottomRight: Radius.circular(8),
                      ),
                    ),
                    child: Text(
                      '模版',
                      style: textStyle(12, Color(0xff292929), FontWeight.w400),
                    ),
                  );
                if (isOrg)
                  return Container(
                    padding: EdgeInsets.symmetric(horizontal: 6, vertical: 2),
                    decoration: BoxDecoration(
                      color: Color(0xff0360FC),
                      borderRadius: BorderRadius.only(
                        topLeft: Radius.circular(8),
                        bottomRight: Radius.circular(8),
                      ),
                    ),
                    child: Text(
                      '素材',
                      style: textStyle(12, Colors.white, FontWeight.w400),
                    ),
                  );
                return SizedBox.shrink();
              }()),
          Visibility(
              visible: !hasLoad && isNew,
              child: Container(
                width: 90.w,
                height: 90.h,
                decoration: const BoxDecoration(
                  color: Color(0x80000000),
                  borderRadius: BorderRadius.all(Radius.circular(8)),
                ),
              )),
          Positioned(
              left: 0,
              right: 0,
              top: 0,
              bottom: 0,
              child: Visibility(
                  visible: status == 2 && isNew,
                  child: Center(
                    child: Image.asset(
                      'ai_record_failed.webp'.aiPath,
                      width: 20.w,
                    ),
                  )))
        ],
      ),
    );
  }
}
